﻿using System;
using System.Windows.Input;

namespace WP2BE.ViewModel
{
    /// <summary>
    /// Relay command for MVVM.
    /// </summary>
    public class RelayCommand : ICommand
    {

        private readonly Func<bool> _canExecute;
        private readonly Action _execute;
        #region Implementation of ICommand

        public RelayCommand(Action execute) : this(execute, null)
        {
        }

        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }
            this._execute = execute;
            this._canExecute = canExecute;
        }
        public void Execute(object parameter)
        {
            this._execute();
        }

        public bool CanExecute(object parameter)
        {
            return this._canExecute == null || _canExecute();
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (this._canExecute != null)
                {
                    CommandManager.RequerySuggested += value;
                }
            }
            remove
            {
                if (this._canExecute != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }

        #endregion
    }
}
